package com.itheima.question.controller;

import com.itheima.pojo.Config.Result;
import com.itheima.swagger.Config.FastDFSClientUtil;
import com.itheima.swagger.contants.RedisConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/question")
@Api(value = "文件上传接口", tags = "admin_user", description = "用于实现各种文件上传")
public class FileUploadController {

    @Autowired
    private FastDFSClientUtil clientUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public String uploadFile(MultipartFile file) {
        try {
            //判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }
            String fileId = clientUtil.uploadFile(file);
            //写入redis
            redisTemplate.opsForSet().add(RedisConstants.ALL_PIC,fileId);
            return fileServerUrl + fileId;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "文件上传失败";
    }
}
